package com.wzm.moviepic.fragment;

import java.io.File;
import java.text.NumberFormat;
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import net.tsz.afinal.FinalBitmap;
import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.http.AjaxCallBack;
import net.tsz.afinal.http.AjaxParams;





import com.wzm.bean.DownInfo;
import com.wzm.bean.PicInfo;
import com.wzm.cache.ConfigCache;
import com.wzm.db.DBHelper;
import com.wzm.manager.AppConfig;
import com.wzm.manager.AppManager;
import com.wzm.manager.Tag;
import com.wzm.moviepic.AppApplication;
import com.wzm.moviepic.R;
import com.wzm.utils.Logger;
import com.wzm.utils.NetworkUtils;

import android.content.Context;
import android.content.Intent;

import android.os.AsyncTask;

import android.os.Environment;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

public class DownAdapter extends BaseAdapter {
	
	//电影的下载队列
	private ArrayList<DownInfo> mList = null;
	private Context mContext = null;
	private LayoutInflater  mInflater;	
	//private int CurDownId = 0; 	
	private FinalHttp fh = null;
	
	//private int CurImg = 0;
	
	//单个电影的图片库
	private ArrayList<PicInfo> pList = null;
	
	DownAdapter(Context context,ArrayList<DownInfo> list)
	{		
		mContext = context;
		mList = list;
		mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);			
		fh = new FinalHttp();		
	}
	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return mList.size();
	}

	@Override
	public Object getItem(int arg0) {
		// TODO Auto-generated method stub
		return mList.get(arg0);
	}

	@Override
	public long getItemId(int arg0) {
		// TODO Auto-generated method stub
		return arg0;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		// TODO Auto-generated method stub
		View view = convertView;
		ViewHolder viewHolder = null;
		if(view == null)
		{
			view = mInflater.inflate(R.layout.down_item, parent, false);   
			viewHolder = new ViewHolder();
			viewHolder.movie_name = (TextView)view.findViewById(R.id.movie_name);
			viewHolder.movie_downshow = (TextView)view.findViewById(R.id.movie_downshow);
			viewHolder.btn_operator = (ImageView)view.findViewById(R.id.btn_operator);
			viewHolder.pbar = (ProgressBar)view.findViewById(R.id.progressBar1);
			view.setTag(viewHolder);
		}else{
			viewHolder = (ViewHolder) view.getTag();
		}
		final DownInfo di = mList.get(position);
		viewHolder.movie_name.setText(di.getMoviename());
		
		
		if(di.getState()==0)
		{//处于暂停中
			viewHolder.btn_operator.setImageResource(R.drawable.download_start);
			viewHolder.pbar.setVisibility(View.INVISIBLE);
		}else{			
			viewHolder.btn_operator.setImageResource(R.drawable.download_stop);
			
			if(di.getSize()==di.getCurpage())
			{
				viewHolder.pbar.setVisibility(View.INVISIBLE);
			}else{
				if(AppApplication.mNetWorkState==0)
				{
					viewHolder.pbar.setVisibility(View.INVISIBLE);
				}else{
					viewHolder.pbar.setVisibility(View.VISIBLE);
				}
				
			}
			
		}
		
		
		
		if(di.getSize()==0)
		{
			viewHolder.movie_downshow.setText("0%");
			//di.getMovieid()			
		}else{
			//下载中更新
			float persent = ((float)(di.getCurpage()+1)/(float)di.getSize());
			//viewHolder.movie_downshow.setText(String.valueOf(persent)+"%");
			String strper = NumberFormat.getPercentInstance().format(persent); 
			viewHolder.movie_downshow.setText(strper);
			//Logger.info(di.getCurpage()+"VS"+di.getSize());
			if(di.getSize()-1==di.getCurpage())
			{//下载完成
				viewHolder.pbar.setVisibility(View.INVISIBLE);
				viewHolder.btn_operator.setImageResource(R.drawable.download_complete);
				viewHolder.btn_operator.setOnClickListener(null);
				AppApplication.getInstance().getfMap().put(di.getMovieid(), di);
				
				if(di.getId()==AppApplication.getInstance().getCurDownid())
				{
					Intent uiintent = new Intent(Tag.UPDATELIST);
			        mContext.sendBroadcast(uiintent); 
			        uiintent = null;
				}								
			}
		}
		
		
		
		viewHolder.btn_operator.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Logger.error("发送开始下载");
				
				if(AppApplication.mNetWorkState!=NetworkUtils.NETWORN_NONE)
				{
					if(di.getState()==0)
					{//开始下载
						Intent service = new Intent(Tag.START);
						service.putExtra("action", Tag.StartMovie);
						service.putExtra("movieid", di.getMovieid());
					    mContext.startService(service);
					}else{
						Logger.error("设置"+di.getMovieid()+"为暂停状态");
						AppApplication.getInstance().getDMap().get(di.getMovieid()).setState(0);
						notifyDataSetChanged(); 
					}
				}else{
					Toast.makeText(mContext, "网络检测失败，请检查网络", Toast.LENGTH_SHORT).show();
				}
				
				
			}
		});
		
//		if (position == selectItem) {  
//			if(viewHolder.lly_operator.getVisibility()==View.GONE)
//			{
////				zoomin = AnimationUtils.loadAnimation(mContext,R.anim.zoomin);	
////				viewHolder.mLayout.setAnimation(zoomin);
//				viewHolder.lly_operator.setVisibility(View.VISIBLE);
//				
//				//按钮事件  开始／暂停  删除
//				String curMovieid = String.valueOf(AppApplication.getInstance().getCurDownMovie());
//				if(curMovieid.equals(di.getMovieid()))
//				{//如果已经在下载  （开始按钮隐藏）
//					viewHolder.btn_start.setVisibility(View.GONE);
//				}else{
//					//暂停按钮隐藏
//					viewHolder.btn_pause.setVisibility(View.GONE);
//				}
//				//开始按钮点击事件
//				viewHolder.btn_start.setOnClickListener(new OnClickListener() {					
//					@Override
//					public void onClick(View v) {
//						// TODO Auto-generated method stub
//						
//					}
//				});
//				//停止按钮点击事件
//				viewHolder.btn_pause.setOnClickListener(new OnClickListener() {
//					
//					@Override
//					public void onClick(View v) {
//						// TODO Auto-generated method stub
//						
//					}
//				});
//				//删除按钮点击事件
//				viewHolder.btn_del.setOnClickListener(new OnClickListener() {
//					
//					@Override
//					public void onClick(View v) {
//						// TODO Auto-generated method stub
//						
//					}
//				});
//				
//				
//				
//				
//			}else{				
//				viewHolder.lly_operator.setVisibility(View.GONE);
//			}       	
//        }else {  
//        	viewHolder.lly_operator.setVisibility(View.GONE);
//        }     
		
		
		return view;
	}
	
	public  void setSelectItem(int selectItem) {  
        this.selectItem = selectItem;  
	}  
	private int  selectItem=-1;  
	
	
	private class ViewHolder {   
		//电影名
        public TextView  movie_name; 
        //电影下载百分比显示
        public TextView movie_downshow;
        //操作菜单
        public ImageView btn_operator;
        //滚动条
        public ProgressBar pbar;
        
    };
    
    public void updateUI()
    {    	    	    	
    	notifyDataSetChanged(); 	   	
    }
    
    
	public ArrayList<PicInfo> excuteJson(String rejson,String movieid)
	{
    	ArrayList<PicInfo> pList = new ArrayList<PicInfo>();
		try {
			JSONObject result = new JSONObject(rejson);
			int status = result.getInt("status");
			if(status==1)
			{
				ConfigCache.setUrlCache(rejson, AppConfig.GETMOVIEINFO+movieid);    
				JSONArray list = result.getJSONArray("story");
				for(int i=0;i<list.length();i++)
				{
					JSONObject obj = list.getJSONObject(i);
					PicInfo pinfo = new PicInfo();
					pinfo.setId(obj.getString("id"));
					pinfo.setImage(obj.getString("image"));
					pinfo.setIntro(obj.getString("intro"));
					pinfo.setpIndex(obj.getString("pindex"));
					pList.add(pinfo);
				}
				
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			//e.printStackTrace();
		}
		return pList;
	}
	
	
	
    
}
